define(function(require, exports){
	var $ = require("jquery");
	var pubjs = require('pubjs');
	var util = require('util');
	var view  = require('@base/view');

	var Main = view.container.extend({
		init:function(config){
			var user = pubjs.getUserCurrent();
			var showAgent = user.Type === 4;
			var showGetResult = pubjs.checkRight('qualificationGetResult') || false;
			config = pubjs.conf(config, {
				// 手动更新状态url
				'verifyUrl': 'qualification/getVerifyState',
				'syncUrl': 'user/syncEmployee',
				'class': 'P-adminAptitudeList',
				'view_model': {
					'showAgent': showAgent,
					'showGetResult': showGetResult
				},
			});
			this.Super('init', arguments);
		},
		afterBuild:function(){
			var self = this;
			var c = self.getConfig();
			var el = self.getDOM();

			var dom = $([
				'<div class="M-formHead">',
					'<span class="ml10 addButton" pub-name="addButton" pub-mod="@base/common/drop.add" ></span>',
					'<span class="ml10" pub-name="verify" pub-mod="@base/common/drop.add" ></span>',
				'</div>',
				'<div class="cl" pub-name="grid" pub-mod="admin/aptitude/grid/list.base"/>'
			].join(''));
			
			var User = pubjs.getUser();
			if(User && !User.isEmployee) {
				dom.eq(0).append('<span class="ml10" pub-access="*" pub-name="sync" pub-mod="@base/common/drop.add" ></span>');
			}

			dom.appendTo(el);
			self.buildFromTemplate({
				'grid': {
					'hasSearch': true,
					'hasFilter': true,
					'hasMenu': true
				},
				'addButton': {
					'def': LANG('新建广告主'),
					'href': '#admin/aptitude/edit',
					'href_target': '_self'
				},
				'verify': {
					'def': LANG('查看审核状态'),
					'icon': 'icon-setting2',
					'href': '#admin/aptitude/verify',
					'href_target': '_self'
				},
				'sync': {
					'def': LANG('同步员工列表'),
					'icon': '',
					'useCallback': true
				},
				'update': {
					'def': LANG('手动更新状态'),
					'icon': 'icon-spinner',
					'useCallback': true
				}
			});

			this.createAsync('slotSidebar', '@layout/v1/sidebar.base', {
				'target': c.targetSidebar,
				'height': 150,
				'items': [
					// {'name': 'showSub', 'uri':'modules/sideBarBase.checkbox', 'config': {
					// 	'title': LANG('结果设置：'),
					// 	'data': [
					// 		{id: 1, name: LANG('只显示代理客户提交的资质')}
					// 	]
					// }},
					{'name': 'status', 'uri':'modules/sideBarBase.radio','config':{
						'title': LANG('状态：'),
						'data': [
							{id: 0, name: LANG('有效')},
							{id: 1, name: LANG('已归档')},
						],
						'value': 0
					}}
				]
			});

			// 审核状态tip
			self.createAsync('tipStatus', 'admin/aptitude/modules/statusTip.main');
		},
		onOperateMenuShow: function(ev){
			var returnList = [];
			var data = ev.param;
			if (!data.IsDeleted) {
				if(data.isOwner){
					if(pubjs.checkRight('qualification.update')){
						returnList.push({
							'id':'edit',
							'name':LANG('编辑')
						});
					}
					if(pubjs.checkRight('qualification.remove')){
						returnList.push({
							'id':'remove',
							'name':LANG('归档')
						});
					}
				}
				
				var User = pubjs.getUser();
				if(!User.isEmployee && pubjs.checkRight('sunfei.qualificationGetResult')) {
					returnList.push({
						'id':'refStaff',
						'name':LANG('关联账号')
					});
				}
			} else {
				if(pubjs.checkRight('qualification.recover')) {
					returnList.push({
						'id':'recover',
						'name':LANG('还原')
					});
				}
			}

			ev.returnValue = returnList;
			return false;
		},
		onOperateMenuSelect: function(ev){
			var self = this;
			var key = ev.param[0]['key'];
			var data = ev.param[1];
			var id = data._id;

			switch (key){
				case 'edit':
					pubjs.controller.navigate('admin/aptitude/edit/' + id);
					break;
				case 'remove':
					pubjs.confirm(LANG('真的要删除 (%1) 资质吗?', data.UserName), function(isOk){
						if (isOk) {
							pubjs.mc.send('qualification/remove', {_id: id}, self.afterRemove.bind(self));
						}
					});
					break;
				case 'refStaff': // 强制更新

					self.showRefStaffPop(data);
					break;
				case 'recover':
					pubjs.confirm(LANG('真的要还原 (%1) 资质吗?', data.UserName), function(isOk){
						if (isOk) {
							pubjs.mc.send('qualification/recover', {_id: id}, self.afterRecover.bind(self));
						}
					});
					break;
			}
		},
		afterRemove: function(err, data) {
			if(err)
			{
				pubjs.alert(err.message);
				return;
			}

			pubjs.alert(LANG('删除成功'));
			// 刷新列表
			this.reload();
		},
		afterRecover: function(err, data) {
			if (err) {
				pubjs.alert(err.message);
				return;
			}
			pubjs.alert(LANG('还原成功'));
			// 刷新列表
			this.reload();
		},
		//强制更新提交资质审核请求
		// audit: function(data){
		// 	var exchangeIds = [];
		// 	util.each(data.Info, function(item){
		// 		if (!item.IsDeleted) {
		// 			exchangeIds.push(+item.ExchangeId);
		// 		}
		// 	});
		// 	if (!exchangeIds.length) {
		// 		return false;
		// 	}

		// 	pubjs.mc.send(
		// 		'qualification/getVerifyState',
		// 		[
		// 			{
		// 				'Id': data._id,
		// 				'ExchangeIds': exchangeIds
		// 			}
		// 		],
		// 		function(err, data){
		// 			if (err) {
		// 				pubjs.alert(err);
		// 				return false;
		// 			}
		// 			pubjs.alert(LANG('更新请求提交成功'));
		// 		}
		// 	);
		// },

		//关联员工按钮
		showRefStaffPop: function(data){
			// todo chuangji 增加一个关联字段

			var refStaff = this.get('refStaff');
			if(!refStaff){
				this.createAsync('refStaff','admin/aptitude/popwin/refStaff.main',function(mod){
					mod.reset().setData(data).show();
				});
			}else{
				refStaff.reset().setData(data).show();
			}
			return this;
		},
		onSelectStaffSuccess: function(ev){
			this.reload();
		},
		// 获取在审核状态的渠道
		getAptitudeGroup: function() {
			var data = this.$.grid.getData();
			var result = [];
			util.each(data.items, function(item) {
				var tmp = {};
				tmp['Id'] = item._id;
				util.each(item.Info, function(item_info){
					//未删除的渠道，审核通过和待审核状态的渠道，不获取审核消息
					if(item_info && !item_info.IsDeleted && (+item_info.Status != 1 || +item_info.Status !== 0)){
						if(!tmp['ExchangeIds']){
							tmp['ExchangeIds'] = [];
						}
						tmp['ExchangeIds'].push(item_info.ExchangeId);
					}
				});
				if(tmp['ExchangeIds'] && tmp['ExchangeIds'].length){
					result.push(tmp);
				}
			});
			return result;
		},
		// 手动更新审核状态
		// refreshStatus: function() {
		// 	var self = this;
		// 	var url = self.getConfig('verifyUrl');
		// 	self.showLoading();
		// 	var data = self.getAptitudeGroup();

		// 	pubjs.mc.send(url, data, self.afterRefreshStatus.bind(self));
		// },
		afterRefreshStatus: function(err, data) {
			this.hideLoading();
			if(err){
				pubjs.error(err.message);
			}
			this.$.grid.load();
		},
		reload: function(param){
			this.$.grid.reload(param);
		},
		onInputClick: function(ev){
			// 手动更新状态按钮点击事件
			if(ev.name == 'update'){
				this.refreshStatus();
			}
			else if(ev.name == 'sync') {
				var c = this.getConfig();
				pubjs.confirm(LANG("确定要同步员工列表吗"), function (yes) {
					if(yes) {
						pubjs.loading.show();
						pubjs.mc.send(c.syncUrl, function (err, data) {
							pubjs.loading.hide();
							if(err) {
								return pubjs.alert(LANG("同步失败" + err.message));
							}
							
							pubjs.alert(LANG("同步成功，记录数： %1",data));
						});
					}
				})
			}

			return false;
		},
		//响应右边侧边栏选项
		onSidebarFilter: function(ev){
			var self = this
				,param = {};

			util.each(ev.param, function(item, idx){
				var type = idx;
				// var id = item.id;

				switch (type) {
					case 'showSub':
						if(item.data && item.data.length){
							util.each(item.data, function(sub){
								if(sub){
									switch (sub.id){
										case 1:
											param.IsAgent = sub.checked ? true : false;
											break;
									}
								}
							});
						}
						break;
					case 'status':
						if (item.data && item.data.length) {
							param.IsDraft = false;
							switch(item.data[0].id) {
								case 1:
									param.IsDeleted = 1;
									break;
								case 2:
									param.IsDraft = true;
									break;
								default:
									param.IsDeleted = 0;
									break;
							}
						}
						break;
				}
			});

			self.$.grid.reload(param);
		},
		onAptitudeSaveSuccess: function() {
			this.$.grid.reload();
			return false;
		},
		// 表格审核状态点击，展示tooltip
		onShowStatusTip: function(ev) {
			var data = ev.param;
			var id = data.id;
			var tipStatus = this.$.tipStatus;
			if (!tipStatus.isShow() || this.$lastStatusId != id) {
				this.$lastStatusId = id;
				tipStatus.show().load(id);
				var options = {
					'anchor': data.elm,
					'pos': 'ml'
				};
				var height = util.getCssValue(tipStatus.getContainer(), 'height');
				var vh = util.getViewport().height;
				var bh = vh - data.clientY;
				if ((height + 35)/2 > bh){
					options['pos'] = 'tm';
				}
				if (height/2 > data.clientY){
					options['pos'] = 'bm';
					options.offsetX = 1;
				}
				tipStatus.update(options);

			} else {
				tipStatus.hide();
			}
		},
		load: function(){
			this.$.grid.reload();
		}
	});
	exports.main = Main;
});